package main

import (
	proto "com/hr/go-muke/grpc/protobuf"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"time"
)

/**
 * @Description
 * @Author huran
 * @Date
 * @Param
 * @return
 **/
type customCredentials struct {
}

// GetRequestMetadata 专门放md
func (c *customCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appid":  "sdfsfd",
		"appkey": "234",
	}, nil
}

// RequireTransportSecurity indicates whether the credentials requires
// transport security.
func (c *customCredentials) RequireTransportSecurity() bool {
	return false
}
func main() {
	credentials := grpc.WithPerRPCCredentials(&customCredentials{})
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithInsecure())
	opts = append(opts, credentials)
	opts = append(opts, grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()
		//md := metadata.New(map[string]string{
		//	"appid": "sdfs",
		//})
		//ctx = metadata.NewOutgoingContext(context.Background(), md)
		err := invoker(ctx, method, req, reply, cc, opts...)
		fmt.Println("耗时:\n", time.Since(start))
		return err
	}))
	conn, err := grpc.NewClient("0.0.0.0:9999", opts...)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	client := proto.NewHelloClient(conn)
	hello, err := client.Hello(context.Background(), &proto.HelloRequest{Name: "DSF", Age: 23})
	fmt.Println(hello, err)
}
